package com.cy.pj.sys.service;

import com.cy.pj.common.annotation.RequiredLog;
import com.cy.pj.common.exception.ServiceException;
import com.cy.pj.common.vo.PageObject;
import com.cy.pj.sys.entity.SysLog;
import com.cy.pj.sys.mapper.SysLogMapper;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SysLogServiceImpl implements SysLogService{
    @Autowired
    private SysLogMapper sysLogMapper;

    @RequiresPermissions("sys:log:view")
    @Override
    public PageObject<SysLog> findPageObjects(
            String userName, Integer pageCurrent) {
        //1.验证参数的合法性
        //1.1 验证pageCurrent的合法性
        //不合法抛出IllegalArgumentException异常
        if(pageCurrent == null || pageCurrent < 1){
            throw new IllegalArgumentException("当前页码不正确");
        }
        //2.基于条件查询总记录数
        //2.1 执行查询
        int rowCount = sysLogMapper.getRowCount(userName);
        //2.2) 验证查询结果，假如结果为0不再执行如下操作
        if(rowCount == 0) throw new ServiceException("系统没有查到对应的记录");

        //3.基于条件查询当前页记录(pageSize定义为2)
        //3.1定义pageSize
        int pageSize = 5;
        //3.2计算startIndex
        int startIndex=(pageCurrent - 1)*pageSize;
        //3.3执行当前数据的查询操作
        List<SysLog> records =
                sysLogMapper.findPageObjects(userName,startIndex,pageSize);
        //4.对分页信息及当前页记录进行封装
        //4.1构建PageObject对象
        PageObject<SysLog> pageObject = new PageObject<>();
        //4.2封装数据
        pageObject.setPageCurrent(pageCurrent)
                .setPageSize(pageSize).setRowCount(rowCount)
                .setRecords(records).setPageCount((rowCount -1) / pageSize + 1);
        return pageObject;
    }

    @RequiresPermissions("sys:log:delete")
    @RequiredLog(operation = "删除日志")
    @Override
    @Transactional
    public int deleteObjects(Integer... ids) {
        //1.判断参数合法性
        if(ids == null || ids.length == 0){
            throw new IllegalArgumentException("请选择一个");
        }
        //2.执行删除操作
        int rows;
        try {
            rows = sysLogMapper.deleteObjects(ids);
        }catch (Throwable e){
            e.printStackTrace();
            //3.如果删除时发生异常,则发出报警信息
            throw new ServiceException("系统故障,正在修复");
        }
        //4.对结果进行验证
        if(rows == 0){
            throw  new ServiceException("记录可能已经不存在");
        }
        //5.返回结果
        return rows;
    }


    @Override
    public void saveObject(SysLog entity) {
        sysLogMapper.insertObject(entity);
    }


}
